package com.springx.examples.showcase.common.exception;

import com.springx.examples.showcase.common.domain.Message;
import com.springx.modules.mapper.JsonMapper;
import com.springx.modules.utils.Exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by test on 2015/8/5.
 */
@ControllerAdvice
public class DefaultExceptionHandler {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    String DEFAULT_ERROR_VIEW = "error/500";
    String DEFAULT_CHARSET="UTF-8";
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public String exception(NativeWebRequest request, Exception ex) {
        logger.error(Exceptions.getStackTraceAsString(ex));
        if (!(request.getHeader("accept").indexOf("application/json") > -1 || (
                request.getHeader("X-Requested-With") != null && request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))) {
            request.setAttribute("error",ex.getMessage(), RequestAttributes.SCOPE_REQUEST);
            return DEFAULT_ERROR_VIEW; //返回一个逻辑视图名
        }
        try {
            HttpServletResponse response =  request.getNativeResponse(HttpServletResponse.class);
            response.setStatus(HttpStatus.OK.value());
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setCharacterEncoding(DEFAULT_CHARSET);
            Message message= null;
            if(ex instanceof  IllegalArgumentException){
                message = new Message(Message.StatusType.ERROR,ex.getMessage());
            }else{
                message = new Message(Message.StatusType.ERROR,"系统异常,请稍后再试", ex.getMessage());
            }

            response.getWriter().write(JsonMapper.nonDefaultMapper().toJson(message));
        } catch (IOException e) {
            logger.error(Exceptions.getStackTraceAsString(ex));
        }
        return null;

    }

}
